package com.maxd.modules.captcha.service;

import com.google.code.kaptcha.Producer;
import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.modules.captcha.entity.SysCaptcha;
import com.maxd.modules.captcha.respository.SysCaptchaRepository;
import com.maxd.modules.chat.entity.Chat;
import com.maxd.modules.chat.entity.ChatContent;
import com.maxd.modules.chat.respository.ChatContentRepository;
import com.maxd.modules.chat.respository.ChatRepository;
import com.maxd.modules.chat.service.ChatContentService;
import com.maxd.utils.DateUtil;
import com.maxd.utils.DateUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class SysCaptchaServiceImpl implements SysCaptchaService {

    @Autowired
    private Producer producer;
    @Autowired
    private SysCaptchaRepository sysCaptchaRepository;

    @Override
    public BufferedImage getCaptcha(String uuid) {
        if(StringUtils.isBlank(uuid)){
            return null;
        }
        //生成文字验证码
        String code = producer.createText();

        SysCaptcha captchaEntity = new SysCaptcha();
        captchaEntity.setUuid(uuid);
        captchaEntity.setCode(code);
        //5分钟后过期
        captchaEntity.setExpireTime(DateUtils.addMinutes(new Date(), 5));
        sysCaptchaRepository.save(captchaEntity);

        return producer.createImage(code);
    }

    @Override
    public boolean validate(String uuid, String code) {
        SysCaptcha captchaEntity = sysCaptchaRepository.findByUuid(uuid);
        if(captchaEntity == null){
            return false;
        }

        //删除验证码
        sysCaptchaRepository.deleteSysCaptchaByUuid(uuid);
        if(captchaEntity.getCode().equalsIgnoreCase(code) && captchaEntity.getExpireTime().getTime() >= System.currentTimeMillis()){
            return true;
        }

        return false;
    }

}
